/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.boot.web.interceptor;

import com.luter.heimdall.core.authorization.handler.HeimdallMethodAuthorizationHandler;
import com.luter.heimdall.core.manager.AuthorizationManager;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 权限注解拦截器,基于 Spring Interceptor 实现
 *
 * @author luter
 */
public class HeimdallAuthorizeAnnotationInterceptor implements HandlerInterceptor {

    /**
     * The Annotation handler.
     */

    private final AuthorizationManager authorizationManager;

    public HeimdallAuthorizeAnnotationInterceptor(AuthorizationManager authorizationManager) {
        this.authorizationManager = authorizationManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        final String requestMethod = request.getMethod();
        if (requestMethod.equalsIgnoreCase(HttpMethod.OPTIONS.name())) {
            //options 请求全部放行
            return true;
        }
        Method m = ((HandlerMethod) handler).getMethod();
        HeimdallMethodAuthorizationHandler.handleMethodAnnotation(authorizationManager, m);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
